<template>
  <div>
    <el-button
      style="float: right" type="primary"
      @click="closeCompare()"
    >
      关闭
    </el-button>
    <div>{{ diffDescription }}</div>
    <div ref="contrastDiv" class="contrast-div"></div>
  </div>
</template>

<script>

require("codemirror/mode/javascript/javascript.js");
import CodeMirror from "codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/addon/merge/merge.js"
import "codemirror/addon/merge/merge.css"
import DiffMatchPatch from "diff-match-patch";

window.diff_match_patch = DiffMatchPatch;
window.DIFF_DELETE = -1;
window.DIFF_INSERT = 1;
window.DIFF_EQUAL = 0;

export default {
  name: "BdpSqlCompare",
  components: {},
  props: {
    value: {
      type: String,
      default: null
    },
    oldv: {
      type: String,
      default: "",
    },
    isReadOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      newValue: "", // 左侧展示文本
      oldValue: "", // 右侧展示文本
      diffDescription: "", // 差异内容描述
    };
  },
  created() {
    this.newValue = this.value
    this.oldValue = this.oldv
  },
  mounted() {
    this.contrast()
  },

  methods: {
    contrast() {
      this.$nextTick(() => {
        const target = this.$refs.contrastDiv;
        target.innerHTML = "";
        let difference = CodeMirror.MergeView(target, {
          value: this.newValue,
          originLeft: null,
          orig: this.oldValue,
          lineNumbers: true,
          mode: "text/x-hive",
          hightlightDifference: true,
          connect: "align",
          readOnly: false,
          // theme: "dracula",
          smartIndent: true,
        });

        let diffCount = difference.right.chunks.length;
        console.log(diffCount)
        let description = "";

        if (diffCount === 0) {
          description = "左右文本内容一致";
        } else if (diffCount === 1) {
          description =
            "共1处差异，差异的开始行号为：" +
            (difference.right.chunks[0].origFrom + 1);
        } else {
          description = "共" + diffCount + "处差异，每处差异的开始行号为：";
          for (let i = 0; i < diffCount; i++) {
            description += difference.right.chunks[i].origFrom + 1;
            if (i !== diffCount - 1) {
              description += "、";
            }
          }
        }
        this.diffDescription = description
      });
    },
    closeCompare() {
      this.newValue = null
      this.oldValue = null
      this.$emit('closeCompare');
    }
  }
}
</script>

<style>

</style>
